package com.newidea.jiangong.service.impi;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newidea.jiangong.component.HeatComponent;
import com.newidea.jiangong.entity.IndoorTemMonitor;
import com.newidea.jiangong.entity.IndoorTemMonitorHead;
import com.newidea.jiangong.mapper.IndoorTemMonitorHeadMapper;
import com.newidea.jiangong.service.IndoorTemMonitorHeadService;
import com.newidea.jiangong.service.IndoorTemMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


@Service
@Slf4j
public class IndoorTemMonitorHeadServiceImpl extends ServiceImpl<IndoorTemMonitorHeadMapper, IndoorTemMonitorHead>
    implements IndoorTemMonitorHeadService {

    /**
     * 采集室温监控的地址
     */
    @Value("${collect.url.indoorTemMonitor}")
    private String indoorTemMonitorUrl;
    /**
     * 采集室温监控分析数据的地址
     */
    @Value("${collect.url.indoorTemMonitorHead}")
    private String indoorTemMonitorHeadUrl;


    private final HeatComponent heatComponent;
    private final IndoorTemMonitorService indoorTemMonitorService;

    public IndoorTemMonitorHeadServiceImpl(
        HeatComponent heatComponent, IndoorTemMonitorService indoorTemMonitorService
    ) {
        this.heatComponent = heatComponent;
        this.indoorTemMonitorService = indoorTemMonitorService;
    }

    /**
     * 采集室温监控数据
     *
     * @param company 所属公司
     * @param token   token
     */
    @Override
    public void collect(String company, String token) {
        // 获取要采集的根部门id
        JSONArray rootDepartments = heatComponent.getRootDepartments(token);
        // 采集数量
        AtomicInteger quantity = new AtomicInteger(0);
        for (int i = 0; i < rootDepartments.size(); i++) {
            JSONObject rootDepartment = rootDepartments.getJSONObject(i);
            String departmentId = rootDepartment.getStr("departmentId");
            // 新增室温监控分析数据
            insertIndoorTemMonitorHead(departmentId, token, company);

            // 新增室温监控数据
            insertIndoorTem(departmentId, token, quantity, company);
        }
        log.info(company + "： 采集室温监控数据：{}条。", quantity);
    }

    /**
     * 新增室温监控分析数据
     *
     * @param departmentId 部门id
     * @param token        token
     * @param company      所属公司
     */
    private void insertIndoorTemMonitorHead(String departmentId, String token, String company) {
        // 请求参数
        JSONObject param = new JSONObject();
        param.set("departmentId", departmentId);
        param.set("beginDate", DateUtil.beginOfDay(DateUtil.yesterday()).toString());
        param.set("endDate", DateUtil.endOfDay(new Date()).toString());
        param.set("groupId", "");

        // 获取室温监控分析数据
        JSONObject data = heatComponent.httpPost(param, indoorTemMonitorHeadUrl, token);

        // 以前数据设置为旧数据
        IndoorTemMonitorHead updateEntity = new IndoorTemMonitorHead();
        updateEntity.setNewest(false);

        QueryWrapper<IndoorTemMonitorHead> updateWrapper = new QueryWrapper<>();
        // 是否获取最新的数据
        updateWrapper.eq("company", company);
        this.update(updateEntity, updateWrapper);

        // 新增室温监控分析数据
        IndoorTemMonitorHead indoorTemMonitorHead = data.toBean(IndoorTemMonitorHead.class);
        indoorTemMonitorHead.setCompany(company);
        indoorTemMonitorHead.setCreateTime(DateUtil.now());
        indoorTemMonitorHead.setNewest(true);
        this.save(indoorTemMonitorHead);
        log.info(company + "： 采集室温监控分析数据成功。");
    }


    /**
     * 新增室温监控数据
     *
     * @param departmentId 部门id
     * @param token        token
     * @param company      所属公司
     */
    private void insertIndoorTem(
        String departmentId, String token, AtomicInteger quantity, String company
    ) {
        String paramStr = "{\"departmentId\":\"1717469205139427328\",\"pageNum\":1,\"pageSize\":1000," +
            "\"viewColumnNames\":[\"column1\"],\"type\":0}";
        // 请求参数
        JSONObject param = JSONUtil.parseObj(paramStr);
        param.set("departmentId", departmentId);

        // 以前数据设置为旧数据
        IndoorTemMonitor updateEntity = new IndoorTemMonitor();
        updateEntity.setNewest(false);

        QueryWrapper<IndoorTemMonitor> updateWrapper = new QueryWrapper<>();
        // 是否获取最新的数据
        updateWrapper.eq("company", company);
        indoorTemMonitorService.update(updateEntity, updateWrapper);

        String now = DateUtil.now();
        // 新增室温监控数据，包括分页数据
        insertPagingData(param, token, quantity, now, company);
    }

    /**
     * 新增室温监控数据，包括分页数据
     *
     * @param param    请求参数
     * @param token    token
     * @param quantity 采集数量
     * @param company  所属公司
     */
    private void insertPagingData(
        JSONObject param, String token, AtomicInteger quantity, String now, String company
    ) {
        // 获取机房监控数据
        JSONObject data = heatComponent.httpPost(param, indoorTemMonitorUrl, token);
        // 获取采集数据
        JSONArray list = data.getJSONArray("list");
        // 插入获取的当前页数据
        if (CollUtil.isNotEmpty(list)) {
            List<IndoorTemMonitor> indoorTemMonitors = list.toList(IndoorTemMonitor.class);
            for (IndoorTemMonitor indoorTemMonitor : indoorTemMonitors) {
                indoorTemMonitor.setCompany(company);
                indoorTemMonitor.setNewest(true);
                indoorTemMonitor.setCreateTime(now);
            }
            indoorTemMonitorService.saveBatch(indoorTemMonitors);
        }
        // 累加采集数量
        quantity.addAndGet(list.size());
        // 是否有下一页
        if (data.getBool("hasNextPage")) {
            // 获取下一页数据
            param.set("pageNum", param.getInt("pageNum") + 1);
            insertPagingData(param, token, quantity, now, company);
        }
    }
}
